<template>
  <div class="active">
    <h2>供应商评审总分与排名</h2>
    <el-table :data="supplierReviews" border style="width: 100%">
      <el-table-column
        prop="key"
        label="序号"
        width="81"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplierCode"
        label="供应商编码"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplierName"
        label="报名供应商"
        width="207"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="priceScore"
        label="价格分"
        width="80"
        align="center"
        :formatter="formatScore"
      ></el-table-column>

      <el-table-column
        prop="businessScore"
        label="商务分"
        width="80"
        align="center"
        :formatter="formatScore"
      ></el-table-column>
      <el-table-column label="技术分" align="center">
        <template
          v-for="(item, index) in supplierReviews[0]?.technicalScores || []"
          :key="index"
        >
          <el-table-column
            :prop="`technicalScores[${index}]`"
            :label="`评委${index + 1}`"
            align="center"
          >
            <template #default="scope">
              <div>
                {{
                  scope.row.technicalScores[index].Info == null
                    ? "/"
                    : scope.row.technicalScores[index]
                }}
              </div>
            </template>
          </el-table-column>
        </template>
        <el-table-column
          prop="averageTechnicalScore"
          label="平均分"
          width="70"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="totalScore"
        label="综合得分"
        width="100"
        align="center"
        fixed="right"
      ></el-table-column>
      <el-table-column
        prop="rank"
        label="排名"
        width="70"
        align="center"
        fixed="right"
      ></el-table-column>
    </el-table>
    <h3>项目评审结果</h3>
    <!-- 项目评审结果 -->
    <el-table
      :data="projectReviews"
      border
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        prop="key"
        label="序号"
        width="81"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="applyTime"
        label="报名时间"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplierCode"
        label="供应商编码"
        width="200"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="报名供应商"
        width="300"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="资质审查"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="score"
        label="综合得分"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="reviewResult"
        label="评审结果"
        width="100"
        align="center"
      ></el-table-column>
    </el-table>
    <h3>项目中止结果确认</h3>
    <el-form :model="SelectedForm" label-width="250px">
      <el-form-item label="第一候选人：">
        <el-select
          v-model="SelectedForm.outbidOneId"
          disabled
          placeholder="请待主持人选择"
          style="width: 500px"
        >
          <el-option
            v-for="candidate in candidates"
            :key="candidate.id"
            :label="candidate.name"
            :value="candidate.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <div v-for="(item, index) in SelectedForm.Signlist">
        <el-form-item label="评委签名确认结果时间：">
          <el-input
            placeholder="待签到"
            style="width: 500px"
            v-model="item.restartCheckTime"
            disabled
          ></el-input>
          <span class="link" @click="StartSingin">评委评审结果确认签名</span>
        </el-form-item>
        <el-form-item
          :label="`评委(${item.name})评审结果确认签名：`"
          :key="index"
        >
          <div class="tablet">
            <el-image
              v-if="item.restartCheck"
              :src="baseURL + item.restartCheck"
            >
              <template #error>
                <div class="image-slot"></div>
              </template>
            </el-image>
          </div>
        </el-form-item>
      </div>
      <sxb ref="Tablet" @Return="Return" style="display: none" />
      <div class="endbutton">
        <el-button @click="prevPage">上一步</el-button>
        <!-- <el-button type="primary" @click="submitForm">提交</el-button> -->
        <!-- <el-button type="danger" @click="terminate">强制终止</el-button> -->
      </div>
    </el-form>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import { judgeProjectInfo } from "@/api/project.js";
import { getDictList, getDict, nowTime, getdict } from "@/utils/common.js";
import {
  totalScore,
  projectInfoAndSupplierAndJudge,
  choiceSupplier,
  endJudgeSign,
  startJudgeSign,
  auditsign,
} from "@/api/examine.js";

import sxb from "@/components/sxb.vue";
const emit = defineEmits(["next-step"]);
const route = useRoute();
const id = computed(() => route.query.id);
const judgeId = ref("");
const userInfo = computed(() => JSON.parse(localStorage.getItem("judgeInfo")));
const Tablet = ref(null);
// 定义数据
const baseURL = import.meta.env.VITE_APP_BASE_API;
const SelectedForm = ref({
  outbidOneId: "",
  remarkOne: "",
  outbidTwoId: "",
  remarkTwo: "",
  outbidThreeId: "",
  remarkThree: "",
  restartCheckTime: "",
  restartCheck: "",
  Signlist: [],
  supervisorSignature: "",
});
const props = defineProps({
  Info: {
    type: Object,
    default: {},
  },
});
const judgeInfo = ref({});
const supplierReviews = ref([]);
const projectReviews = ref([]);
const Stop = ref("");
const candidates = ref([
  { id: 1, name: "候选人1" },
  { id: 2, name: "候选人2" },
  { id: 3, name: "候选人3" },
]);
const projectInfo = ref({});
const prevPage = () => {
  emit("next-step", 5);
};
const getInfo = (boolean) => {
  SelectedForm.value = {
    outbidOneId: "",
    remarkOne: "",
    outbidTwoId: "",
    remarkTwo: "",
    outbidThreeId: "",
    remarkThree: "",
    restartCheckTime: "",
    restartCheck: "",
    Signlist: [],
    supervisorSignature: "",
  };
  totalScore({ projectId: id.value }).then((res) => {
    if (res.code == "200") {
      supplierReviews.value = [];
      if (res.data.length > 0) {
        for (let i = 0; i < res.data.length; i++) {
          let technicalScores = []; // 技术分数组
          let averageTechnicalScore = null; // 技术平均分
          const scoreMap = {}; // 用于跟踪技术分的累积

          for (let j = 0; j < res.data[i].scoreList.length; j++) {
            const scoreItem = res.data[i].scoreList[j];

            // 根据 type 添加到相应的属性中或进行累加
            if (scoreItem.type === "score_skill") {
              if (!scoreMap[scoreItem.markId]) {
                scoreMap[scoreItem.markId] = scoreItem.score;
                technicalScores.push(scoreItem.score);
              } else {
                // 如果已经存在相同的 markId，则累加分数
                scoreMap[scoreItem.markId] += scoreItem.score;
                // 更新 technicalScores 中对应的值（假设顺序一致）
                const index = technicalScores.findIndex(
                  (score) =>
                    score === scoreMap[scoreItem.markId] - scoreItem.score
                );
                if (index !== -1) {
                  technicalScores[index] = scoreMap[scoreItem.markId];
                }
              }
            } else if (scoreItem.type === "score_average") {
              averageTechnicalScore = scoreItem.score;
            }
          }

          // 构建 supplierReviews.value 数组
          supplierReviews.value.push({
            key: i + 1,
            supplierCode: res.data[i].supplierCode,
            supplierName: res.data[i].supplierName,
            priceScore: null, // 初始化为 null
            businessScore: null, // 初始化为 null
            technicalScores: technicalScores,
            averageTechnicalScore: averageTechnicalScore,
            totalScore: res.data[i].totalScore,
            rank: i + 1,
          });

          // 查找价格分和商务分
          for (let j = 0; j < res.data[i].scoreList.length; j++) {
            const scoreItem = res.data[i].scoreList[j];
            if (scoreItem.type === "score_price") {
              supplierReviews.value[
                supplierReviews.value.length - 1
              ].priceScore = scoreItem.score;
            } else if (scoreItem.type === "score_business") {
              supplierReviews.value[
                supplierReviews.value.length - 1
              ].businessScore = scoreItem.score;
            }
          }

          // 构建 candidates.value 数组
        }
      } else {
        let judgeList = [];
        for (let i = 0; i < props.Info.judgeList.length; i++) {
          if (props.Info.judgeList[i].type == "judge_jury") {
            judgeList.push(props.Info.judgeList[i]);
          }
        }
        for (let i = 0; i < props.Info.supplierList.length; i++) {
          supplierReviews.value.push({
            key: i + 1,
            ...props.Info.supplierList[i],
            technicalScores: judgeList,
            Info: null,
            averageTechnicalScore: "/",
            priceScore: "/",
            businessScore: "/",
            totalScore: "/",
            rank: "/",
          });
        }
      }
      console.log(supplierReviews.value);
    }
  });
  candidates.value = [];
  projectReviews.value = [];
  SelectedForm.value.outbidOneId = props.Info.outbidOneId;
  if (props.Info.breakRemark) {
    Stop.value = true;

    SelectedForm.value.breakRemark = props.Info.breakRemark;
  }

  for (let i = 0; i < props.Info.judgeList.length; i++) {
    switch (props.Info.judgeList[i].type) {
      case "judge_jury":
        if (props.Info.judgeList[i].userId == userInfo.value.id) {
          judgeId.value = props.Info.judgeList[i].id;
          SelectedForm.value.Signlist.push({
            id: props.Info.judgeList[i].id,
            restartCheck: props.Info.judgeList[i].endCheck,
            restartCheckTime: props.Info.judgeList[i].endCheckTime,
            name: props.Info.judgeList[i].name,
          });
          break;
        }
    }
  }

  for (let i = 0; i < props.Info.supplierList.length; i++) {
    candidates.value.push({
      id: props.Info.supplierList[i].supplierId,
      name: props.Info.supplierList[i].name,
    });
    const formattedDateTime = props.Info.supplierList[i].applyTime.slice(0, 16);
    let reviewResult = "";
    if (props.Info.outbidOneId == props.Info.supplierList[i].supplierId) {
      reviewResult = "第一候选人";
    } else {
      reviewResult = "待定";
    }
    projectReviews.value.push({
      key: i + 1,
      applyTime: formattedDateTime,
      supplierCode: props.Info.supplierList[i].supplierCode,
      name: props.Info.supplierList[i].name,
      status:
        props.Info.supplierList[i].status == "apply_supplier_pass"
          ? "符合"
          : "异常",
      score: props.Info.supplierList[i].score,
      reviewResult: reviewResult,
    });
  }
  if (Stop.value == true) {
    candidates.value.push({
      id: "",
      name: "无",
    });
  }
  console.log(projectReviews.value);
  if (boolean) {
    ElMessage({
      message: "刷新成功",
      type: "success",
    });
  }
};

const formatScore = (row, column, cellValue) => {
  return cellValue < 0 ? 0 : cellValue;
};
const Return = (item) => {
  const params = {
    projectId: id.value,
    projectCode: projectInfo.value.oaCode,
    projectJudgeId: judgeId.value,
    signStr: item,
    type: "sign_end",
  };
  auditsign(params).then((res) => {
    if (res.code == "200") {
      getInfo();
    }
  });
};
const StartSingin = () => {
  Tablet.value.beginSign();
};
onMounted(() => {
  getInfo();
});
</script>

<style scoped lang="scss">
@use "./judge";
</style>
